package mn.idax.exchange.otc.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mn.idax.exchange.auth.bean.AuthInfo;
import mn.idax.exchange.auth.util.AuthHelper;
import mn.idax.exchange.auth.util.AuthInfoUtils;
import mn.idax.exchange.common.SpringUtils;
import mn.idax.exchange.common.bean.ResponseData;
import mn.idax.exchange.otc.annotation.LoginAuth;
import mn.idax.exchange.otc.config.AdProducter;
import mn.idax.exchange.otc.constant.CommonConstant;
import mn.idax.exchange.otc.constant.ReferenceExchageConstant;
import mn.idax.exchange.otc.constant.RequestUrlConstant;
import mn.idax.exchange.otc.domain.*;
import mn.idax.exchange.otc.entity.*;
import mn.idax.exchange.otc.enums.AdEnum;
import mn.idax.exchange.otc.enums.DictEnum;
import mn.idax.exchange.otc.enums.LogOrderProcessEnum;
import mn.idax.exchange.otc.enums.OTCBeneficiarysEnum;
import mn.idax.exchange.otc.enums.response.OTCAdResponseEnum;
import mn.idax.exchange.otc.exception.DynamicException;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.mapper.OTCOrderMapper;
import mn.idax.exchange.otc.service.*;
import mn.idax.exchange.otc.service.impl.MemoryService;
import mn.idax.exchange.otc.service.impl.RedisService;
import mn.idax.exchange.otc.util.*;
import mn.idax.exchange.otc.util.function.OrderProcessLogFunction;
import mn.idax.exchange.otc.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static java.util.Optional.ofNullable;
import static mn.idax.exchange.otc.service.OTCThreadPool.THREAD_POOL;

/**
 * @Auther: shihaiming
 * @Date: 2018/08/06
 * @Description:
 */

@Api(value = "广告", tags = {"广告"})
@RequestMapping(RequestUrlConstant.MODULE_AD)
@RestController
public class AdController {

    @Autowired
    private OTCAdsService otcAdsService;
    @Autowired
    private OTCSysDictionaryItemService otcSysDictionaryItemService;
    @Autowired
    private OTCBeneficiarysService otcBeneficiarysService;
    @Autowired
    private OTCAdWayService otcAdWayService;
    @Autowired
    private OTCUserService otcUserService;
    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private FileUrlService fileUrlService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private BusinessApplyService businessApplyService;

    @Autowired
    private AdProducter adProducter;

    @Autowired
    private OTCOrderMapper otcOrderMapper;

    private static ExecutorService executorService = Executors.newFixedThreadPool(3);

    /**
     * 创建广告
     *
     * @param adRequest
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "创建广告", notes = "(shihaiming，自测通过)<b>注意点:</b><br/> 1、交易类型 1-出售 2-购买 <br/>2、广告状态 1.上架 2.下架 3.过期 <br/>3、当前支持的币种名称：BTC、ETH、EOS、USDT")
    @RequestMapping(value = RequestUrlConstant.AD_CREATE, method = RequestMethod.POST)
    public ResponseData create(@Valid @RequestBody OTCAdRequest adRequest,
                               HttpServletRequest request) throws Exception {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        User user = userService.getUserById(userId);
        //账户是虚拟账户不允许发广告
        if (user.getIsfake()) {
            throw new IdaxException(OTCAdResponseEnum.PUBLISH_AD_NO_AUTH.getCode());
        }

        //限制只能承兑商发广告 app 2.3 限制回归
        if (businessApplyService.isbusinesser(userId) < 1 && !adRequest.getPairname().equalsIgnoreCase("EAT")) {
            throw new IdaxException(OTCAdResponseEnum.NOT_BUSINESSER_AD_PUBLISH.getCode());
        }

        //高级认证完成后才可以发广告 cuiyongshu 2019/06/04
//        if (!user.getIsadvancedcertificate()) {
//            throw new IdaxException(OTCAdResponseEnum.REQUIRED_REAL_NAME_AUTH.getCode());
//        }
        //用户被限制作场外交易
        if (redisService.isForbideUser(userId)){
            throw new IdaxException(OTCAdResponseEnum.USER_IS_FORBIDDEN.getCode());
        }

        //用户输入的国家和法币是否和支付方式对应
        if (!otcAdsService.payTypeIsMatch(adRequest.getCountry(), adRequest.getUnit(), adRequest.getTrademode())) {
            throw new IdaxException(OTCAdResponseEnum.PAYMETHOD_CURRENCY_ERROR.getCode());
        }

        //检查交易币种信息
        OTCSysDictionaryItem otcSysDictionaryItem = checkCoin(adRequest.getPairname(), userId, adRequest.getType());

        List<OTCSysDictionaryItem> listItem = otcSysDictionaryItemService.listItem(DictEnum.AD_EXPIRE_TIME.getCode());
        //获取过期间隔天数
        Integer expireIntervalDay = ofNullable(listItem).map(item -> item.get(0).getItemvalue()).orElse(0);

        Date currDate = DateUtils.getUTCNow();

        //校验请求参数是否合法
        validRequestParam(adRequest, otcSysDictionaryItem, userId);

        // 发布广告限制修改（每个币种，买卖方向只能发布3条广告，共6条）
        if (this.otcAdsService.verifyPublishAdvertising(userId, otcSysDictionaryItem.getItemvalue(), adRequest.getType())) {
            throw new IdaxException(OTCAdResponseEnum.PUBLISH_AD_REPEAT.getCode());
        }


        //获取过期日期
        Date expireDate = DateUtils.addDay(currDate, expireIntervalDay);

        OTCAds adInfo = new OTCAds();
        BeanUtils.copyProperties(adRequest, adInfo);
        adInfo.setMinprice(adRequest.getMinPrice());
        adInfo.setMaxprice(adRequest.getMaxPrice());
        //id为自增字段
        adInfo.setId(null);
        adInfo.setPairid(otcSysDictionaryItem.getItemvalue());

        adInfo.setPublisherid(userId);
        adInfo.setPublishsource(ParamUtils.getRequestSourceCode(request));
        adInfo.setExpiretime(expireDate);
        //其他时间设置
        adInfo.setCreatetime(currDate);
        adInfo.setPublishtime(currDate);
        adInfo.setUpdatetime(currDate);
        adInfo.setState(AdEnum.state_up.getCode());
        adInfo.setNumber(adRequest.getNumber());


        //广告为卖单时 发广告人勾选的支付方式 自己必须有
//        if (adRequest.getType().intValue() == AdEnum.type_sell.getCode().intValue()){
//            if (!judgeTradeMode(adRequest.getTrademode(),userId)){
//                throw new IdaxException(OTCAdResponseEnum.PAYMETHOD_NOT_ENOUGH.getCode());
//            }
//        }

        //查询广告发布者的收款账号信息
        List<OTCAdWay> otcAdWayList = new ArrayList<OTCAdWay>();
        for (int i = 0; i < adRequest.getTrademode().length; i++) {
            OTCBeneficiarys param = new OTCBeneficiarys();
            param.setUserid(userId);
            param.setDictitemid(adRequest.getTrademode()[i]);
            OTCBeneficiarys otcBeneficiarys = otcBeneficiarysService.selectByUserIDAndType(param);

            //出售广告才需要必填收款方式
            if (AdEnum.type_sell.getCode().equals(adRequest.getType())) {
                if (otcBeneficiarys == null) {
                    throw new IdaxException(OTCAdResponseEnum.RECEIVE_ACCOUNT_NOT_EXIST.getCode());
                }
            }

            //创建广告交易方式
            OTCAdWay otcAdWay = new OTCAdWay();
            otcAdWay.setBeneficiaryid(otcBeneficiarys == null ? 0 : otcBeneficiarys.getId());
            otcAdWay.setCreatetime(currDate);
            otcAdWay.setTradetype(otcBeneficiarys == null ? adRequest.getTrademode()[i] : otcBeneficiarys.getDictitemid());
            otcAdWay.setUpdatetime(currDate);
            otcAdWay.setUserid(userId);

            otcAdWayList.add(otcAdWay);
        }

        otcAdsService.addOTCAds(adInfo, otcAdWayList);

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    adProducter.sendUpAdMessage(JSON.toJSONString(new SyncAdInMemory(adInfo.getId(),adInfo.getPublisherid())));
                } catch (Exception e) {
                    LogUtils.warn(this.getClass(),"createAdInMemory fail, " + ExceptionUtils.getStackTrace(e));
                }
            }
        });

        return ResponseData.success();
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OTCPayModeDetailService otcPayModeDetailService;
    /**
     * 校验请求参数是否合法
     *
     * @param adRequest
     * @param otcSysDictionaryItem
     */
    private void validRequestParam(OTCAdRequest adRequest, OTCSysDictionaryItem otcSysDictionaryItem, Integer userId) throws Exception {

        MarketPairs marketPairs = new MarketPairs();
        marketPairs.setMarketPairs(adRequest.getPairname().concat(adRequest.getUnit()));
        marketPairs.setCountry(adRequest.getCountry());

        //获取行情价格
//        String redisKey = ReferenceExchageConstant.redisExchangeFileName + ":" + marketPairs.getMarketPairs();
//        List<ExchageMarketPrice> exchageMarketPrices = JsonUtil.readValue(redisTemplate.opsForValue().get(redisKey), new TypeReference<List<ExchageMarketPrice>>() {
//        });
//
//        if (exchageMarketPrices.isEmpty()) {
//            throw new IdaxException(OTCAdResponseEnum.EXCHANGE_PRICE_EMPTY.getCode());
//        }

//        otcPayModeDetailService.changeFloatingPrice(exchageMarketPrices,marketPairs);

        if (adRequest.getIsfloating()) {

//            //如果是浮动类型的广告，交易所需要对应
//            if (exchageMarketPrices.stream().noneMatch(p -> p.getExchange().equals(adRequest.getExchange()))){
////            if (StringUtils.isEmpty(adRequest.getExchange())) {
//                LogUtils.warn(this.getClass(),"exchangeValidFail ,exchange " + adRequest.getExchange() + "exchageMarketPrices: " + JSON.toJSONString(exchageMarketPrices));
//                throw new IdaxException(OTCAdResponseEnum.EXCHANGE_NO_MATCH.getCode());
//            }

//            //用户传的价格在浮动价格之间即可,取用户传的价格 不再计算最新的价格 下单时还是根据参考交易所和浮动率算 不影响 app 2.3
//            List<ExchageMarketPrice> collect = exchageMarketPrices.stream().filter(p -> p.getExchange().equals(adRequest.getExchange()))
//                    .collect(Collectors.toList());
//
//            ExchageMarketPrice exchageMarketPrice = collect.get(0);
//            if(adRequest.getFloatingrate().compareTo(exchageMarketPrice.getFloatingRate()) > 0
//                    || adRequest.getFloatingrate().compareTo(exchageMarketPrice.getFloatingRate().multiply(new BigDecimal("-1"))) < 0){
//                throw new IdaxException(OTCAdResponseEnum.LESS_EXCHANGE_MINPRICE.getCode());
//            }


        } else {
            //非浮动价格广告 浮动率 0 交易所empty
            if (!StringUtils.isEmpty(adRequest.getExchange()) || adRequest.getFloatingrate().compareTo(BigDecimal.ZERO) != 0) {
                throw new IdaxException(OTCAdResponseEnum.FLOATINGAD_MISMATCH.getCode());
            }
        }

        //出售价必须大于0
        if (new BigDecimal("0").compareTo(adRequest.getPrice()) >= 0) {
            throw new IdaxException(OTCAdResponseEnum.PRICE_MUST_GREATER_ZERO.getCode());
        }
        //最小限额必须大于0
        if (new BigDecimal("0").compareTo(adRequest.getMinamount()) >= 0) {
            throw new IdaxException(OTCAdResponseEnum.MIN_AMMOUNT_MUST_GREATER_ZERO.getCode());
        }
        //最大限额不能小于最小限额
        if (adRequest.getMinamount().compareTo(adRequest.getMaxamount()) > 0) {
            throw new IdaxException(OTCAdResponseEnum.MAX_AMMOUNT_MUST_GREATER_MIN_AMMOUNT.getCode());
        }
        //下单价格应在浮动价格区间内 固定价格关闭的,不受浮动率影响 浮动价格拿浮动率算
        if (!MemoryService.CLOSEDFIXEDSWITCH.containsKey(adRequest.getCountry())){
            if (adRequest.getMinPrice().compareTo(adRequest.getPrice()) > 0 || adRequest.getMaxPrice().compareTo(adRequest.getPrice()) < 0 ) {
                throw new IdaxException(OTCAdResponseEnum.FLOATPRICE_EXCEEDING.getCode());
            }
        }

        //检查广告类型
        if (!AdEnum.type_buy.getCode().equals(adRequest.getType()) && !AdEnum.type_sell.getCode().equals(adRequest.getType())) {
            throw new IdaxException(OTCAdResponseEnum.PARAMETER_TYPE_ERROR.getCode());
        }

        OTCSysDictionaryItem otcSysDictionaryItem2=otcSysDictionaryItemService.getItemByDictIdAndItemValue(10,1230);

        /**
         * 根据广告类型判断买币数量
         */
        //广告为购买-买单 购买广告最大限额分别不超过20btc、200eth、200000usdt
        if (AdEnum.type_buy.getCode().equals(adRequest.getType())) {
            //获取字典表中最大购买量的dictId  todo 下面的map拿上来
            List<OTCSysDictionaryItem> listItem = otcSysDictionaryItemService.listItem(DictEnum.AD_PUBLISH_AMOUNT_LIMIT.getCode());
            OTCSysDictionaryItem buyAdMaxLimit = otcSysDictionaryItemService.getItemByDictIdAndItemValue(listItem.get(0).getDictid(), otcSysDictionaryItem.getItemvalue());
            if (new BigDecimal(buyAdMaxLimit.getItemdesc()).compareTo(adRequest.getMaxamount()) == -1) {
                throw new DynamicException(OTCAdResponseEnum.BEYOND_MAX_BUY_LIMIT.getCode(), listItem.get(0).getItemdesc(), listItem.get(1).getItemdesc(), listItem.get(2).getItemdesc());
            }

            if(Boolean.valueOf(otcSysDictionaryItem2.getItemdesc())){
                //广告价差校验
                checkPrice(adRequest,AdEnum.type_sell.getCode());
            }

        } else {
            //广告为出售-卖单 最大交易限额 / 设置的价格 < 所含币种数量
            //获取用户当前币种的数量
            Account account = accountService.getAccountByCoinIdAndUserId(userId, otcSysDictionaryItem.getItemvalue());
            if (adRequest.getIsfloating()) {
                Map<String, String> map = otcSysDictionaryItemService.getMinamountAndMaxAmount(
                        new ValidateQuota(adRequest.getUnit(), adRequest.getPairname()), userId);
                String availableamount = map.get("availableamount");
                String currencyQuota = map.get("currencyQuota");

                if (adRequest.getPrice().compareTo(adRequest.getMinPrice()) <0 ){
                    throw new IdaxException(OTCAdResponseEnum.LESS_EXCHANGE_MINPRICE.getCode());
                }

                if (adRequest.getPrice().compareTo(adRequest.getMaxPrice()) > 0 ){
                    throw new IdaxException(OTCAdResponseEnum.BEYOND_EXCHANGE_MAXPRICE.getCode());
                }
                BigDecimal price = adRequest.getPrice();

                if (adRequest.getMinamount().compareTo(new BigDecimal(currencyQuota)) == -1) {
                    throw new IdaxException(OTCAdResponseEnum.LESS_MIN_SELL_LIMIT.getCode());
                } else if (adRequest.getMaxamount().compareTo(new BigDecimal(availableamount).
                        multiply(price.multiply((CommonConstant.HUNDRED).add(adRequest.getFloatingrate())).divide(CommonConstant.HUNDRED))) == 1) {
                    LogUtils.warn(this.getClass(),"publishFloatingSellAd maxamount is " + adRequest.getMaxamount() + ",accountAviable is " +new BigDecimal(availableamount).
                            multiply(price.multiply((CommonConstant.HUNDRED).add(adRequest.getFloatingrate())).divide(CommonConstant.HUNDRED)));
                    throw new IdaxException(OTCAdResponseEnum.BEYOND_MAX_SELL_LIMIT.getCode());
                }
            } else {

                if (account == null || (adRequest.getMaxamount().divide(adRequest.getPrice(), 8, BigDecimal.ROUND_DOWN).compareTo(account.getAvailableamount()) == 1)) {
                    LogUtils.warn(this.getClass(),"publishUnfloatingSellAd account is " + account + ",availableamount is " + account.getAvailableamount() + " ，req maxamount is "
                            + adRequest.getMaxamount().divide(adRequest.getPrice(), 8, BigDecimal.ROUND_DOWN));
                    throw new IdaxException(OTCAdResponseEnum.BEYOND_MAX_SELL_LIMIT.getCode());
                }
            }

            int result = adRequest.getNumber().compareTo(account.getAvailableamount());
            if(result==1){
                throw new IdaxException(OTCAdResponseEnum.BEYOND_MAX_BALANCE_LIMIT.getCode());
            }

            if(Boolean.valueOf(otcSysDictionaryItem2.getItemdesc())) {
                //广告价差校验
                checkPrice(adRequest, AdEnum.type_buy.getCode());
            }
        }
    }


    /**
     * 广告价差校验
     * @param adRequest
     */
    public void checkPrice(OTCAdRequest adRequest,Integer type)throws Exception{

//        String keyStr = AdEnum.type_sell.getCode().equals(type) ? "OTCAD_PRICE:SELL" : "OTCAD_PRICE:BUY";
//        // 外盘拟合判断
//        String price = redisTemplate.opsForValue().get(keyStr);
//
//        BigDecimal spread;
//        if(!StringUtils.isEmpty(price) && new BigDecimal(price).compareTo(BigDecimal.ZERO) == 1){
//            spread = adRequest.getPrice().subtract(new BigDecimal(price));
//        }else{
//            OTCOrder otcOrder=otcOrderMapper.getFinishLastOrder(type);
//            spread = adRequest.getPrice().subtract(otcOrder.getPairprice());
//        }
//
//        OTCSysDictionaryItem otcSysDictionaryItem1=otcSysDictionaryItemService.getItemByDictIdAndItemValue(10,1209);
//        //判断价差是否大于正负0.05
//        if (spread.signum() == -1) {
//            if(spread.compareTo(new BigDecimal("-"+otcSysDictionaryItem1.getItemdesc()))==-1){
//                throw new IdaxException(OTCAdResponseEnum.LESS_EXCHANGE_SPREARD.getCode());
//            }
//        }else if(spread.signum() == 0){
//            System.out.println("这是一个0");
//        }else {
//            if(spread.compareTo(new BigDecimal(otcSysDictionaryItem1.getItemdesc()))==1){
//                throw new IdaxException(OTCAdResponseEnum.LESS_EXCHANGE_SPREARD.getCode());
//            }
//        }
    }


    @ApiOperation(value = "我的广告详情-app", notes = "我的广告详情-app")
    @RequestMapping(value = RequestUrlConstant.AD_MYAD_DETAIL, method = RequestMethod.POST)
    public ResponseData myAdDetail(@RequestBody ADQueryDTO adQueryDTO, HttpServletRequest request) throws Exception {

        //检查id
        if (adQueryDTO == null || (Objects.isNull(adQueryDTO.getAdId()) || adQueryDTO.getAdId().intValue() < 1)){
            throw new IdaxException(OTCAdResponseEnum.ID_NOT_EXIST.getCode());
        }

        //广告详情
        OTCAds otcAds = otcAdsService.selectByPrimaryKey(adQueryDTO.getAdId());
        if (otcAds == null){
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        if (authInfo == null) {
            authInfo = AuthHelper.getInstance(null).decodeToken(request.getHeader("token"));
        }
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        if (!otcAds.getPublisherid().equals(userId)){
            throw new IdaxException(OTCAdResponseEnum.AD_NOT_BELONG_YOU.getCode());
        }

        return ResponseData.success(otcAdsService.getMyAdDetail(otcAds,userId,request));
    }
    /**
     * 根据id获取指定广告详情
     *
     * @param
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "获取指定广告详情", notes = "获取指定广告详情，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_INFO, method = RequestMethod.POST)
    @LoginAuth(disable = true)
    public ResponseData info(@RequestBody ADQueryDTO adQueryDTO, HttpServletRequest request) throws Exception {
        //检查id
        if (adQueryDTO == null || (Objects.isNull(adQueryDTO.getAdId()) || adQueryDTO.getAdId().intValue() < 1)){
            throw new IdaxException(OTCAdResponseEnum.ID_NOT_EXIST.getCode());
        }

        //广告详情
        OTCAds otcAds = otcAdsService.selectByPrimaryKey(adQueryDTO.getAdId());
        if (otcAds == null){
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        //add by kwan @ 2019-02-15
        if (authInfo == null) {
            authInfo = AuthHelper.getInstance(null).decodeToken(request.getHeader("token"));
        }
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);


        //add by kwan @ 2019-02-15
        //当前用户是否发布人
        final boolean isCurrUserPublisher = userId.equals(otcAds.getPublisherid());
        //非上架状态，且当前用户不是发布人，不予展示
        if (!isCurrUserPublisher && !AdEnum.state_up.getCode().equals(otcAds.getState())) {
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }

        if (otcAds.getIsfloating()) {
            otcAds.setPrice(otcAdsService.floatingAdsPriceConvert(
                    new FloatingPriceDTO(otcAds.getType(), otcAds.getMinprice(), otcAds.getMaxprice(),
                            otcAds.getUnit(), otcAds.getExchange(), otcAds.getPairname(), otcAds.getPrice(), otcAds.getFloatingrate())
            ).getPrice());
        }
        otcAds.setRowversion(null);
        List<OTCADBeneficiarysDTO> payModeList = new ArrayList<OTCADBeneficiarysDTO>();
        ADInfoDTO adInfoDTO = new ADInfoDTO();
        List<Integer> list = Lists.newArrayList();
        //相应广告支持的支付交易方式
        list = otcAdWayService.selectDisplayTradeTypeByAdId(adQueryDTO.getAdId());
        if (list != null && list.size() > 0) {
            OTCBeneficiarys record = new OTCBeneficiarys();
            record.setUserid(otcAds.getPublisherid());

            list.forEach(adId -> {
                record.setDictitemid(adId);
                OTCBeneficiarys otcbs = otcBeneficiarysService.selectByUserIDAndType(record);
                OTCADBeneficiarysDTO dto = new OTCADBeneficiarysDTO();

                if (otcbs != null && isCurrUserPublisher) {
                    dto.setAccount(otcbs.getAccount());
                    dto.setAttachmenturl(fileUrlService.dealFileUrlAddress(otcbs.getAttachmenturl()));
                    dto.setBankname(otcbs.getBankname());
                    dto.setName(otcbs.getName());
                    dto.setSubbranchbankname(otcbs.getSubbranchbankname());
                }

                dto.setTradetype(record.getDictitemid());
                dto.setPayTypeIcon(OTCPayTypeNationUtils.getPayTypeIcon(record.getDictitemid()));
                payModeList.add(dto);
            });
        }
        // 广告小数为数据
        otcAds.setMinamount(otcAds.getMinamount().setScale(6,BigDecimal.ROUND_DOWN));
        otcAds.setMaxamount(otcAds.getMaxamount().setScale(6,BigDecimal.ROUND_DOWN));
        adInfoDTO.setPayModeList(payModeList);
        adInfoDTO.setOtcAds(otcAds);
        adInfoDTO.setAdTradeNotified(SpringUtils.getMessage("message." + CommonConstant.ADTRADENOTIFIED));
        adInfoDTO.setUsdtCny(getUSDTCNY(otcAds.getPairname()+otcAds.getUnit()));
        LogUtils.info(this.getClass(),"info_response:"+JSON.toJSONString(adInfoDTO));
        return ResponseData.success(adInfoDTO);

    }

    /**
     * 获取USDTCNY
     * @return
     * @throws Exception
     */
    public String getUSDTCNY(String pair)throws Exception{
//        String redisKey = ReferenceExchageConstant.redisExchangeFileName + ":" + pair;
//        String redisResult = redisTemplate.opsForValue().get(redisKey);
        String redisResult =  MemoryService.SYSTEMSETTINGMAP.get(pair).toString();
        if(StringUtils.isEmpty(redisResult)){
            return "6.98";
        }
        List<ExchageMarketPrice> exchageMarketPrices = JsonUtil.readValue(redisResult, new TypeReference<List<ExchageMarketPrice>>() {
        });

        return exchageMarketPrices.get(0).getPrice().toString();
    }

    /**
     * 编辑广告
     *
     * @param adRequest
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "编辑广告", notes = "编辑广告，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_UPDATE, method = RequestMethod.POST)
    public ResponseData update(@Valid @RequestBody OTCAdRequest adRequest,
                               HttpServletRequest request) throws Exception{

        //检查id
        if (adRequest.getId() == null || adRequest.getId() < 1) {
            throw new IdaxException(OTCAdResponseEnum.ID_NOT_EXIST.getCode());
        }

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        //检查交易币种信息
        OTCSysDictionaryItem otcSysDictionaryItem = checkCoin(adRequest.getPairname(), userId, adRequest.getType());

        OTCAds otcAds = otcAdsService.selectByPrimaryKey(adRequest.getId());
        //判断修改人与发布人是否是同一人
        if (otcAds == null || !userId.equals(otcAds.getPublisherid())) {
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }

        //非下架的广告不可编辑
        if (!AdEnum.state_down.getCode().equals(otcAds.getState())) {
            throw new IdaxException(OTCAdResponseEnum.NOT_DOWN_NO_EDIT.getCode());
        }

        //修改前的部分信息不能修改
        if (!adRequest.getCountry().equals(otcAds.getCountry()) || !adRequest.getUnit().equals(otcAds.getUnit())
                || !adRequest.getType().equals(otcAds.getType()) || !adRequest.getPairname().equals(otcAds.getPairname())){
            throw new IdaxException(OTCAdResponseEnum.UPDATE_AD_UNCHANGELESS.getCode());
        }

        //用户输入的国家和法币是否和支付方式对应
        if (!otcAdsService.payTypeIsMatch(adRequest.getCountry(), adRequest.getUnit(), adRequest.getTrademode())) {
            throw new IdaxException(OTCAdResponseEnum.PAYMETHOD_CURRENCY_ERROR.getCode());
        }

        //校验请求参数是否合法
        validRequestParam(adRequest, otcSysDictionaryItem, userId);

        Date currDate = DateUtils.getUTCNow();

        //查询广告发布者的收款账号信息
        List<OTCAdWay> otcAdWayList = new ArrayList<OTCAdWay>();
        for (Integer tradeType : adRequest.getTrademode()) {
            OTCBeneficiarys param = new OTCBeneficiarys();
            param.setUserid(userId);
            param.setDictitemid(tradeType);
            OTCBeneficiarys otcBeneficiarys = otcBeneficiarysService.selectByUserIDAndType(param);
            //出售广告才需要必填收款方式
            if (AdEnum.type_sell.getCode().equals(adRequest.getType())) {
                if (otcBeneficiarys == null || !otcBeneficiarys.getUserid().equals(userId)) {
                    throw new IdaxException(OTCAdResponseEnum.RECEIVE_ACCOUNT_NOT_EXIST.getCode());
                }
                //与产品沟通 不需要 2018-11-28 cys
//                if (!otcBeneficiarys.getIsdisplay()) {
//                    throw new IdaxException(OTCAdResponseEnum.RECEIVE_ACCOUNT_NOT_DISPLAY.getCode());
//                }
            }

            //创建广告交易方式
            OTCAdWay otcAdWay = new OTCAdWay();
            otcAdWay.setBeneficiaryid(ofNullable(otcBeneficiarys).map(OTCBeneficiarys::getId).orElse(0));
            otcAdWay.setCreatetime(currDate);
            otcAdWay.setTradetype(ofNullable(otcBeneficiarys).map(OTCBeneficiarys::getDictitemid).orElse(tradeType));
            otcAdWay.setUpdatetime(currDate);
            otcAdWay.setUserid(userId);
            otcAdWay.setAdid(otcAds.getId());

            otcAdWayList.add(otcAdWay);
        }

        OTCAds adInfo = new OTCAds();
        BeanUtils.copyProperties(adRequest, adInfo);
        adInfo.setMinprice(adRequest.getMinPrice());
        adInfo.setMaxprice(adRequest.getMaxPrice());
        adInfo.setId(otcAds.getId());
        adInfo.setPairid(otcSysDictionaryItem.getItemvalue());
        adInfo.setUpdatetime(currDate);

        otcAdsService.updateOTCAds(adInfo, otcAdWayList);
        return ResponseData.success();
    }

    /**
     * 检查用户是否有该币种的账号信息
     * 检查用户币种可用余额是否大于最低数量限制
     *
     * @param pairname 币种名称
     * @param userId   用户id
     * @param type
     * @return
     */
    private OTCSysDictionaryItem checkCoin(String pairname, Integer userId, Integer type) {
        LogUtils.info(this.getClass(), "---检查币种----userId" + userId + "，pairname：" + pairname);
        //获取交易币种信息
        OTCSysDictionaryItem otcSysDictionaryItem = this.otcSysDictionaryItemService.getItemByDesc(DictEnum.COIN_CODE.getCode(), pairname);
        if (otcSysDictionaryItem == null) {
            throw new IdaxException(OTCAdResponseEnum.TRANSACTION_CURRENT_NOT_EXIST.getCode());
        }

        //出售广告   用户账户的数字货币余额须达到一定数量时，广告才可被展示
        if (AdEnum.type_sell.getCode().equals(type)) {
            AccountDTO accountDTO = new AccountDTO();
            //交易币种主键id
            accountDTO.setCoinid(otcSysDictionaryItem.getItemvalue());
            //用户id
            accountDTO.setUserid(userId);
            AccountDTO account = otcAdsService.selectAvailableAmountByUserIdAndCoinId(accountDTO);
            if (account == null) {
                throw new IdaxException(OTCAdResponseEnum.COIN_ACCOUNT_NOT_EXIST.getCode());
            }

            List<OTCSysDictionaryItem> coinAmountList = otcSysDictionaryItemService.listItem(DictEnum.COIN_AMOUNT_MINIMUM_LIMIT.getCode());
            if (coinAmountList != null && coinAmountList.size() > 0) {
                for (OTCSysDictionaryItem sysDictionaryItem : coinAmountList) {
                    //对比coinid
                    if (sysDictionaryItem.getItemvalue().equals(otcSysDictionaryItem.getItemvalue())) {
                        String minCoinAmount = sysDictionaryItem.getItemdesc();
                        //可用余额大于等于最低限制时，才可以显示上架
                        if (account.getAvailableAmount().compareTo(new BigDecimal(minCoinAmount)) >= 0) {
                            return otcSysDictionaryItem;
                        }
                    }
                }
            }
            throw new IdaxException(OTCAdResponseEnum.COIN_ACCOUNT_NOT_ENOUGH.getCode());
        }

        return otcSysDictionaryItem;
    }

    /**
     * 下架广告
     *
     * @param
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "下架广告", notes = "下架广告，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_DOWN, method = RequestMethod.POST)
    public ResponseData down(@RequestBody ADQueryDTO adQueryDTO, HttpServletRequest request){
        //检查id
        if (adQueryDTO == null || adQueryDTO.getAdId() < 1) {
            throw new IdaxException(OTCAdResponseEnum.ID_NOT_EXIST.getCode());
        }

        // 获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        OTCAds otcAds = otcAdsService.selectByPrimaryKey(adQueryDTO.getAdId());
        //判断修改人与发布人是否是同一人，非同一人不可以操作
        if (otcAds == null || !userId.equals(otcAds.getPublisherid())) {
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }

        //非下架状态的广告才可以更新成下架
        if (AdEnum.state_down.getCode().equals(otcAds.getState())) {
            throw new IdaxException(OTCAdResponseEnum.IS_DOWN_NO_DOWN.getCode());
        }

        OTCAds adInfo = new OTCAds();
        adInfo.setId(adQueryDTO.getAdId());
        adInfo.setState(AdEnum.state_down.getCode());
        adInfo.setUpdatetime(DateUtils.getUTCNow());

        otcAdsService.updateOTCAdsStateById(adInfo);

        //将广告从内存中移除
        otcAdsService.removeAdFromMemory(otcAds.getId(),userId);
        LogUtils.info(this.getClass(), "UserDownAd adId : " + otcAds.getId());

        return ResponseData.success();
    }

    /**
     * 上架广告
     *
     * @param
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "上架广告", notes = "上架广告，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_UP, method = RequestMethod.POST)
    public ResponseData up(@RequestBody ADQueryDTO adQueryDTO, HttpServletRequest request) throws Exception {
        //检查id
        if (adQueryDTO == null || adQueryDTO.getAdId() < 1) {
            throw new IdaxException(OTCAdResponseEnum.ID_NOT_EXIST.getCode());
        }

        // 获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        //用户被限制作场外交易
        if (redisService.isForbideUser(userId)){
            throw new IdaxException(OTCAdResponseEnum.USER_IS_FORBIDDEN.getCode());
        }

//        User user = userService.getUserById(userId);
        //高级认证完成后才可以上架广告 cuiyongshu 2019/06/04  早期任何人都可以发广告，下架的广告还是上架
//        if (!user.getIsadvancedcertificate()) {
//            throw new IdaxException(OTCAdResponseEnum.REQUIRED_REAL_NAME_AUTH.getCode());
//        }

        //限制只能承兑商发广告 app 2.3 限制回归
        if (businessApplyService.isbusinesser(userId) < 1) {
            throw new IdaxException(OTCAdResponseEnum.NOT_BUSINESSER_AD_PUBLISH.getCode());
        }

        OTCAds otcAds = otcAdsService.selectByPrimaryKey(adQueryDTO.getAdId());
        //判断修改人与发布人是否是同一人，非同一人不可以操作
        if (otcAds == null || !userId.equals(otcAds.getPublisherid())) {
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }

        //检查广告状态是否是下架状态
        if (!AdEnum.state_down.getCode().equals(otcAds.getState())) {
            throw new IdaxException(OTCAdResponseEnum.NOT_DOWN_NO_UP.getCode());
        }

        // 上架广告限制修改（每个币种，买卖方向只能发布3条广告，共6条）
        if (this.otcAdsService.verifyPublishAdvertising(userId, otcAds.getPairid(), otcAds.getType())) {
            throw new IdaxException(OTCAdResponseEnum.PUBLISH_AD_REPEAT.getCode());
        }

        //检查币种信息与账号余额
        checkCoin(otcAds.getPairname(), userId, otcAds.getType());

        List<OTCSysDictionaryItem> listItem = otcSysDictionaryItemService.listItem(DictEnum.AD_EXPIRE_TIME.getCode());
        //获取过期间隔天数
        Integer expireIntervalDay = ofNullable(listItem).map(item -> item.get(0).getItemvalue()).orElse(0);
        Date currDate = DateUtils.getUTCNow();
        //获取过期日期
        Date expireDate = DateUtils.addDay(currDate, expireIntervalDay);

        OTCAds adInfo = new OTCAds();
        adInfo.setId(adQueryDTO.getAdId());
        adInfo.setState(AdEnum.state_up.getCode());
        adInfo.setUpdatetime(currDate);
        adInfo.setPublishtime(currDate);
        adInfo.setExpiretime(expireDate);

        otcAdsService.updateOTCAdsStateById(adInfo);

        //将广告信息添加进内存
        THREAD_POOL.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    adProducter.sendUpAdMessage(JSON.toJSONString(new SyncAdInMemory(adInfo.getId(),adInfo.getPublisherid())));
                } catch (Exception e) {
                    LogUtils.warn(this.getClass(),"upAdInMemory fail, " + ExceptionUtils.getStackTrace(e));
                }
            }
        });

        return ResponseData.success();
    }

    /**
     * 激活广告
     *
     * @param
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "激活广告", notes = "激活广告，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_ACTIVATE, method = RequestMethod.POST)
    public ResponseData activate(@RequestBody ADActiveDTO adActiveDTO, HttpServletRequest request) {
        if (adActiveDTO == null || adActiveDTO.getAdIds().length == 0) {
            throw new IdaxException(OTCAdResponseEnum.ID_NOT_EXIST.getCode());
        }
        // 获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);

        Date currDate = DateUtils.getUTCNow();

        for (Integer adId : adActiveDTO.getAdIds()) {
            OTCAds otcAds = otcAdsService.selectByPrimaryKey(adId);
            //判断修改人与发布人是否是同一人，非同一人不可以操作
            if (otcAds == null || !userId.equals(otcAds.getPublisherid())) {
                throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
            }

            //检查广告状态是否是过期状态
            if (!AdEnum.state_expire.getCode().equals(otcAds.getState())) {
                throw new IdaxException(OTCAdResponseEnum.NOT_EXPIRED_NO_ACTIVE.getCode());
            }

            OTCAds adInfo = new OTCAds();
            adInfo.setId(adId);
            //广告激活后改为下架状态
            adInfo.setState(AdEnum.state_down.getCode());
            adInfo.setUpdatetime(currDate);

            otcAdsService.updateOTCAdsStateById(adInfo);
        }
        return ResponseData.success();
    }

    /**
     * 获取我的广告列表
     *
     * @param
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取我的广告列表", notes = "获取我的广告列表，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_MYLIST, method = RequestMethod.POST)
    public ResponseData myList(@RequestBody OTCMyAdPageDTO otcMyAdPageDTO, HttpServletRequest request) throws Exception {
        // 获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        Integer pageIndex = otcMyAdPageDTO.getPageIndex();
        Integer pageSize = otcMyAdPageDTO.getPageSize();

        if (pageIndex == null || pageIndex < 0) {
            pageIndex = 0;
        }
        //防止用户恶意攻击
        if (pageSize == null || pageSize <= 0 || pageSize > 1000) {
            pageSize = 1000;
        }
        otcMyAdPageDTO.setPageSize(pageSize);
        otcMyAdPageDTO.setPageIndex(pageIndex);
        otcMyAdPageDTO.setPublisherId(userId);
        ADShowResultDTO adShowResult = otcAdsService.getMyADList(otcMyAdPageDTO);
        return ResponseData.success(adShowResult);
    }

    /**
     * 获取广告列表
     *
     * @param
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取广告列表", notes = "获取广告列表，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_LIST, method = RequestMethod.POST)
    @LoginAuth(disable = true)
    public ResponseData list(@RequestBody OTCAdPageDTO otcAdPageDTO, HttpServletRequest request){
        Integer pageIndex = otcAdPageDTO.getPageIndex();
        Integer pageSize = otcAdPageDTO.getPageSize();

        if (pageIndex == null || pageIndex < 0) {
            pageIndex = 0;
        }
        //防止用户恶意攻击
        if (pageSize == null || pageSize <= 0 || pageSize > 1000) {
            pageSize = 1000;
        }

        otcAdPageDTO.setPageSize(pageSize);
        otcAdPageDTO.setPageIndex(pageIndex);
        ADShowResultDTO adShowResult = new ADShowResultDTO();
        OrderProcessLogFunction.logOrderProcess(s -> {
            ADShowResultDTO baseResult = otcAdsService.getADPage(otcAdPageDTO);
            BeanUtils.copyProperties(baseResult, adShowResult);
        }, this.getClass(), LogOrderProcessEnum.ad_query.getMessage());
        return ResponseData.success(adShowResult);
    }

    /**
     * 获取币种价格
     * @param request
     * @throws Exception
     */
//    @ApiOperation(value = "获取币种价格", notes = "获取币种价格，(shihaiming，自测通过)")
//    @RequestMapping(value = RequestUrlConstant.AD_GET_PRICE,method = RequestMethod.POST)
//    public ResponseData getPrice(@RequestBody CurrencyRequestPriceDTO currencyRequestPriceDTO, HttpServletRequest request) throws Exception{
//    	BigDecimal price = PairUtils.getCoinPriceCny(currencyRequestPriceDTO.getPairname());
//    	Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
//    	map.put("price", price);
//        return ResponseData.success(map);
//    }

    /**
     * 获取币种最高收购价格
     *
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "获取币种最高收购价格", notes = "获取币种最高收购价格，购买时拿最高价，type = 2(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_GET_MAX_PRICE, method = RequestMethod.POST)
    public ResponseData getMaxPrice(@RequestBody RequestCoinPriceDTO requestCoinPriceDTO, HttpServletRequest request){
        BigDecimal price = otcAdsService.getMaxPrice(requestCoinPriceDTO.getPairname());
        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        map.put("price", ofNullable(price).orElse(new BigDecimal("0.00")));
        return ResponseData.success(map);
    }

    /**
     * 获取币种最低出售价格
     *
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "获取币种最低出售价格", notes = "获取币种最低出售价格，出售时拿最低价，type = 1(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_GET_MIN_PRICE, method = RequestMethod.POST)
    public ResponseData getMinPrice(@RequestBody RequestCoinPriceDTO requestCoinPriceDTO, HttpServletRequest request){
        BigDecimal price = otcAdsService.getMinPrice(requestCoinPriceDTO.getPairname());
        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        map.put("price", ofNullable(price).orElse(new BigDecimal("0.00")));
        return ResponseData.success(map);
    }

    /**
     * 根据广告id获取用户的广告汇总信息
     *
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "根据广告id获取用户的广告汇总信息", notes = "根据广告id获取用户的广告汇总信息，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_SUMMARY, method = RequestMethod.POST)
    @LoginAuth(disable = true)
    public ResponseData getADSummaryByAdId(@RequestBody ADQueryDTO adQueryDTO, HttpServletRequest request){
        OTCAds otcAds = otcAdsService.selectByPrimaryKey(adQueryDTO.getAdId());
        if (otcAds != null) {
            OTCUserADSummaryDTO otcUserADSummaryDTO = otcUserService.selectByUserId(otcAds.getPublisherid());
            //此接口不返回用户邮箱
            otcUserADSummaryDTO.setEmail(null);
            otcUserADSummaryDTO.setIsBusinesser(null);
            return ResponseData.success(otcUserADSummaryDTO);
        }
        LogUtils.info(this.getClass(),"getADSummaryByAdId req: " + JSON.toJSONString(adQueryDTO));
        throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
    }

    /**
     * 根据用户UniqueKey获取用户的广告汇总信息
     *
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "根据用户UniqueKey获取用户的广告汇总信息", notes = "根据用户UniqueKey获取用户的广告汇总信息，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_USER_SUMMARY, method = RequestMethod.POST)
    public ResponseData getSummary(@Valid @RequestBody OTCAdUserDTO otcAdUserDTO, HttpServletRequest request){
        OTCUser otcUser = otcUserService.getOTCUserByUniqueKey(otcAdUserDTO.getUniqueKey());
        if (otcUser == null) {
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }
        OTCUserADSummaryDTO otcUserADSummaryDTO = otcUserService.selectByUserId(otcUser.getUserid());
        //此接口不返回用户邮箱
        otcUserADSummaryDTO.setEmail(null);
        return ResponseData.success(otcUserADSummaryDTO);
    }

    /**
     * 获取指定用户发布的广告列表
     *
     * @param
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取指定用户发布的广告列表", notes = "获取指定用户发布的广告列表，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_USER_ADLIST, method = RequestMethod.POST)
    public ResponseData myList(@Valid @RequestBody OTCAdvertiserDTO otcAdvertiserDTO, HttpServletRequest request) throws Exception {
        Integer pageIndex = otcAdvertiserDTO.getPageIndex();
        Integer pageSize = otcAdvertiserDTO.getPageSize();

        if (pageIndex == null || pageIndex < 0) {
            pageIndex = 0;
        }
        //防止用户恶意攻击
        if (pageSize == null || pageSize <= 0 || pageSize > 1000) {
            pageSize = 1000;
        }
        otcAdvertiserDTO.setPageSize(pageSize);
        otcAdvertiserDTO.setPageIndex(pageIndex);
        OTCUser otcUser = otcUserService.getOTCUserByUniqueKey(otcAdvertiserDTO.getUniqueKey());
        if (otcUser == null) {
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }
        otcAdvertiserDTO.setPublisherId(otcUser.getUserid());
        ADShowResultDTO adShowResult = otcAdsService.getOtherUserADList(otcAdvertiserDTO);
        return ResponseData.success(adShowResult);
    }

    /**
     * 获取当前用户的广告汇总信息
     *
     * @param request
     * @throws Exception
     */
    @ApiOperation(value = "获取当前用户的广告汇总信息", notes = "获取当前用户的广告汇总信息，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_MY_SUMMARY, method = RequestMethod.POST)
    public ResponseData getSummary(HttpServletRequest request){
        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        OTCUserADSummaryDTO otcUserADSummaryDTO = otcUserService.getSummaryByUserId(userId);
        return ResponseData.success(otcUserADSummaryDTO);
    }

    /**
     * 根据广告id，查询取当前用户对应币种余额
     *
     * @param
     * @throws Exception
     */
    @ApiOperation(value = "根据广告id，查询取当前用户对应币种余额", notes = "根据广告id，查询取当前用户对应币种余额，(shihaiming，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_MY_COIN_AMOUNT, method = RequestMethod.POST)
    public ResponseData getCoinAmount(@RequestBody ADQueryDTO adQueryDTO){
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        OTCAds otcAds = otcAdsService.selectByPrimaryKey(adQueryDTO.getAdId());
        if (otcAds == null) {
            throw new IdaxException(OTCAdResponseEnum.DATA_NOT_EXIST.getCode());
        }
        AccountDTO accountDTO = new AccountDTO();
        //交易币种主键id
        accountDTO.setCoinid(otcAds.getPairid());
        //用户id
        accountDTO.setUserid(userId);
        AccountDTO account = otcAdsService.selectAvailableAmountByUserIdAndCoinId(accountDTO);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("availableAmount", ofNullable(account).map(AccountDTO::getAvailableAmount).orElse(BigDecimal.ZERO));
        return ResponseData.success(map);
    }

    @ApiOperation(value = "获取信用最高的广告单和最具性价比的广告单", notes = "获取信用最高的广告单和最具性价比的广告单，(jack_huang，自测通过)")
    @RequestMapping(value = RequestUrlConstant.AD_RECOMMENDADS, method = RequestMethod.POST)
    public ResponseData getRecommendAds(@RequestBody RecommendAdsRequest request) throws Exception {


        if (StringUtils.isEmpty(request.getPairname())) {
            throw new IdaxException(OTCAdResponseEnum.COINNAME_NOT_NULL.getCode());
        }
        if (request.getType() == null) {
            throw new IdaxException(OTCAdResponseEnum.TRANSACTION_MODE_NOT_SELECTED.getCode());
        }
        if (request.getType() != 1 && request.getType() != 2) {
            throw new IdaxException(OTCAdResponseEnum.TRANSACTION_ERROR.getCode());
        }
        //法币单位
        if (OTCBeneficiarysEnum.PayUnitEnum.getPayUnit(request.getUnit()) == null) {
            throw new IdaxException(OTCAdResponseEnum.PAYMETHOD_UNIT_ERROR.getCode());
        }
        //支付方式
//        if (OTCBeneficiarysEnum.PayMethodEnum.getTemplate(request.getTransactionWayList()) == null){
//            throw new IdaxException(OTCAdResponseEnum.TRANSACTION_ERROR.getCode());
//        }

        List<ADRecommendListResult> list = otcAdsService.getRecommendAds(request);
        return ResponseData.success(list);
    }


}
